package com.swgk.core.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.model.layer.NullLayer;
import com.swgk.core.R;

import java.lang.reflect.Field;

/**
 * Description:
 * Author zhengkewen
 * Time 2017/12/11
 */
public class MToast {
    private static Toast mToast = null;
    private static String oldMsg;
    private static long oneTime = 0;
    private static long twoTime = 0;

    public static void showToast(Context context, String text) {
        View v = null;
        TextView tv = null;
        if (TextUtils.isEmpty(text)) return;
        if (null == context) return;

        if (mToast == null) {
            mToast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_SHORT);

            LayoutInflater inflate = (LayoutInflater)
                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflate.inflate(R.layout.custom_toast, null);
            tv = (TextView) v.findViewById(R.id.message);
            if (tv == null) return;
            tv.setText(text);
            mToast.setGravity(Gravity.CENTER, 0, 0);
            mToast.setView(v);
            mToast.show();
            oneTime = System.currentTimeMillis();
        } else {
            twoTime = System.currentTimeMillis();
            if (text.equals(oldMsg)) {
                if (twoTime - oneTime > 1000) {
                    // 这里是判断toast上一次显示的时间和这次的显示时间如果大于1000，
                    //  则显示新的toast
                    mToast.cancel();
                    mToast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_SHORT);

                    LayoutInflater inflate = (LayoutInflater)
                            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = inflate.inflate(R.layout.custom_toast, null);
                    tv = (TextView) v.findViewById(R.id.message);
                    if (tv == null) return;
                    tv.setText(text);
                    mToast.setGravity(Gravity.CENTER, 0, 0);
                    mToast.setView(v);
                    mToast.show();
                    oneTime = twoTime;
                }
            } else {
                mToast.cancel();
                mToast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_SHORT);

                LayoutInflater inflate = (LayoutInflater)
                        context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = inflate.inflate(R.layout.custom_toast, null);
                tv = (TextView) v.findViewById(R.id.message);
                if (tv == null) return;
                tv.setText(text);
                oldMsg = text;
                tv.setText(text);
                mToast.setGravity(Gravity.CENTER, 0, 0);
                mToast.setView(v);
                mToast.show();
                oneTime = twoTime;
            }
        }
    }

    public static void showLongToast(Context context, String text) {
        if (null == context) return;
        if (mToast == null) {
            mToast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_LONG);
        }
        LayoutInflater inflate = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(R.layout.custom_toast, null);
        TextView tv = (TextView) v.findViewById(R.id.message);
        tv.setText(text);
        mToast.setGravity(Gravity.CENTER, 0, 0);
        mToast.setDuration(Toast.LENGTH_LONG);
        mToast.setView(v);
        mToast.show();
    }

    /**
     * 自定义toast显示位置
     *
     * @param context
     * @param text
     * @param load    Gravity.CENTER：中间
     *                <p>
     *                Gravity.BOTTOM：下方
     *                <p>
     *                Gravity.TOP：上方
     *                <p>
     *                Gravity.RIGHT：右边
     *                <p>
     *                Gravity.LEFT：左边
     */
    public static void showLongToast(Context context, String text, int load) {
        if (null == context) return;
        if (mToast == null) {
            mToast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_LONG);
        }
        LayoutInflater inflate = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(R.layout.custom_toast, null);
        TextView tv = (TextView) v.findViewById(R.id.message);
        tv.setText(text);
        mToast.setView(v);
        mToast.setGravity(load, 0, 0);
        mToast.show();
    }

    public static void showLongToast1(Context context, String text, int load) {
        if (null == context) return;
        if (mToast != null) {
            mToast = null;
        }
        mToast = Toast.makeText(context.getApplicationContext(), text, Toast.LENGTH_LONG);
        LayoutInflater inflate = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(R.layout.custom_toast, null);
        TextView tv = (TextView) v.findViewById(R.id.message);
        tv.setText(text);
        mToast.setView(v);
        mToast.setDuration(3 * 1000);
        mToast.setGravity(load, 0, 0);
        mToast.show();
    }

    public static void showToast(Context context, int res) {
        if (mToast == null) {
            mToast = Toast.makeText(context.getApplicationContext(), context.getString(res), Toast.LENGTH_SHORT);
        }
        LayoutInflater inflate = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(R.layout.custom_toast, null);
        TextView tv = (TextView) v.findViewById(R.id.message);
        tv.setText(context.getString(res));
        mToast.setGravity(Gravity.CENTER, 0, 0);
        mToast.setDuration(Toast.LENGTH_SHORT);
        mToast.setView(v);
        mToast.show();
    }

    /**
     * 自定义布局的Toast
     *
     * @param context Toast所在Activity
     * @param layout  Toast需要显示的布局文件
     * @param rootId  布局里面的id
     * @param textId  显示toast内容的Text的id
     * @param width   Toast的宽度
     * @param height  Toast的高度
     * @param tip     Toast显示的内容
     */
    public static void shwoCustomToast(Context context, int layout, int rootId, int textId, int width, int height, String tip) {
        View toastView = LayoutInflater.from(context).inflate(layout, null);
        RelativeLayout rootView = toastView.findViewById(rootId);

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams((int) ScaleUtils.dip2px(context, width), (int) ScaleUtils.dip2px(context, height));
        rootView.setLayoutParams(layoutParams);
        TextView toastText = toastView.findViewById(textId);
        toastText.setText(tip);
        Toast toast = initToast(context);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.setView(toastView);
        toast.show();
    }

    /**
     * 初始化/获取mToast对象，适配android 7.1，处理BadTokenException
     *
     * @param context Context
     * @return Toast
     */
    @SuppressLint("ShowToast")
    private static Toast initToast(Context context) {
        if (mToast == null) {
            mToast = Toast.makeText(context.getApplicationContext(), "", Toast.LENGTH_SHORT);
            if (Build.VERSION.SDK_INT == 25) {
                hook(mToast);
            }
        }
        return mToast;
    }

    /**
     * 7.1手机上的BadTokenException 相关处理
     *
     * @param toast Toast对象
     */
    private static void hook(Toast toast) {
        try {
            Object tn = mFieldTN.get(toast);
            Handler preHandler = (Handler) mFieldTNHandler.get(tn);
            mFieldTNHandler.set(tn, new FiexHandler(preHandler));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static Field mFieldTN;
    private static Field mFieldTNHandler;

    static {
        if (Build.VERSION.SDK_INT == 25) {
            try {
                mFieldTN = Toast.class.getDeclaredField("mTN");
                mFieldTN.setAccessible(true);
                mFieldTNHandler = mFieldTN.getType().getDeclaredField("mHandler");
                mFieldTNHandler.setAccessible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 7.1手机上的BadTokenException 相关处理
     */
    private static class FiexHandler extends Handler {
        private Handler impl;

        FiexHandler(Handler impl) {
            this.impl = impl;
        }

        @Override
        public void dispatchMessage(Message msg) {
            try {
                super.dispatchMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void handleMessage(Message msg) {
            impl.handleMessage(msg);
        }
    }

}
